package com.demo.crm.springboot3security.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * 日志脱敏转换器
 */
public class LogMaskConverter extends MessageConverter {
    // 手机号码正则
    private static final Pattern PHONE_PATTERN = Pattern.compile("(\\d{3})(\\d{4})(\\d{4})");

    // 邮箱正则
    private static final Pattern EMAIL_PATTERN = Pattern.compile("(\\w{2})(\\w+)(@\\w+\\.[a-z]+(\\.[a-z]+)?)");

    // 身份证正则
    private static final Pattern ID_CARD_PATTERN = Pattern.compile("(\\d{4})(\\d{10})(\\w{4})");

    // 银行卡号正则
    private static final Pattern BANK_CARD_PATTERN = Pattern.compile("(\\d{4})(\\d+)(\\d{4})");

    @Override
    public String convert(ILoggingEvent event) {
        String message = event.getFormattedMessage();
        if (message == null || message.isEmpty()) {
            return message;
        }

        // 对各类敏感信息进行脱敏处理
        message = maskPhone(message);
        message = maskEmail(message);
        message = maskIdCard(message);
        message = maskBankCard(message);

        return message;
    }

    private String maskPhone(String message) {
        Matcher matcher = PHONE_PATTERN.matcher(message);
        if (matcher.find()) {
            return matcher.replaceAll("$1****$3");
        }
        return message;
    }

    private String maskEmail(String message) {
        Matcher matcher = EMAIL_PATTERN.matcher(message);
        if (matcher.find()) {
            return matcher.replaceAll("$1****$3");
        }
        return message;
    }

    private String maskIdCard(String message) {
        Matcher matcher = ID_CARD_PATTERN.matcher(message);
        if (matcher.find()) {
            return matcher.replaceAll("$1**********$3");
        }
        return message;
    }

    private String maskBankCard(String message) {
        Matcher matcher = BANK_CARD_PATTERN.matcher(message);
        if (matcher.find()) {
            return matcher.replaceAll("$1****$3");
        }
        return message;
    }
}